#!/bin/bash

# 检查系统是否为 openkylin
check_openkylin() {
    if [ -f /etc/os-release ]; then
        source /etc/os-release
        if [[ "$ID" == "openkylin" || "$NAME" == *"openkylin"* ]]; then
            return 0
        else
            echo "错误：此脚本适用于 openkylin 系统"
            echo "当前系统: $NAME"
            return 1
        fi
    else
        echo "错误：当前系统无法自动安装依赖，请从上游软件源内自行下载！"
        return 1
    fi
}

# 安装开发依赖
install_dependencies() {
    echo "开始更新软件包列表..."
    sudo apt update || {
        echo "错误：apt update 失败"
        return 1
    }

    echo "安装基础开发工具..."
    sudo apt install -y build-essential cmake || {
        echo "错误：安装基础开发工具失败"
        return 1
    }

    echo "安装 Kylin SDK 硬件库..."
    sudo apt install -y libkysdk-hardware libkysdk-hardware-dev || {
        echo "错误：安装 Kylin SDK 硬件库失败"
        return 1
    }

    echo "安装 Kylin SDK Qt 组件..."
    sudo apt install -y libkysdk-qtwidgets libkysdk-qtwidgets-dev || {
        echo "错误：安装 Kylin SDK Qt 组件失败"
        return 1
    }

    echo "安装 Kylin SDK Wayland 支持..."
    sudo apt install -y libkysdk-waylandhelper libkysdk-waylandhelper-dev libkf5windowsystem-dev || {
        echo "错误：安装 Kylin SDK Wayland 支持失败"
        return 1
    }

    echo "所有软件包安装成功！"
    return 0
}

# 主函数
main() {
    echo "=== Monitor Overlay 开发环境安装脚本 ==="
    
    # 检查系统
    if ! check_openkylin; then
        exit 1
    fi

    # 检查是否以 root 权限运行
    if [ "$EUID" -eq 0 ]; then
        echo "警告：不建议直接以 root 用户运行此脚本"
        read -p "是否继续？(y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo "安装已取消"
            exit 1
        fi
    fi

    # 确认安装
    echo "即将安装以下开发依赖："
    echo "  - build-essential, cmake"
    echo "  - libkysdk-hardware 及相关开发包"
    echo "  - libkysdk-qtwidgets 及相关开发包"
    echo "  - libkysdk-waylandhelper 及相关开发包"
    echo
    
    read -p "是否继续安装？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "安装已取消"
        exit 0
    fi

    # 执行安装
    if install_dependencies; then
        echo "=== 安装完成 ==="
        echo "所有开发依赖已成功安装！"
    else
        echo "=== 安装失败 ==="
        echo "部分软件包安装失败，请检查错误信息"
        exit 1
    fi
}

# 运行主函数
main "$@"